import es6 from '../lib/es6-promise'

 /** 将wx api Promise异步化 https://mp.weixin.qq.com/debug/wxadoc/dev/api/?t=20161122
  * 用法： const app = getApp()
  *       app.$wx.signIn() 
  *          .then(data => console.log(data))
  *          .catch(e => console.log(e))
  */

class wxService{
    constructor() {
        this.__init()
    }

    __init(){
        const self = this
        const allMethod = Object.keys(wx)
        //缓存同步方法
        const syncMethods = [
            'stopRecord', 
			'pauseVoice', 
			'stopVoice', 
			'pauseBackgroundAudio', 
			'stopBackgroundAudio', 
			'showNavigationBarLoading', 
			'hideNavigationBarLoading', 
			'createAnimation', 
			'createContext', 
			'hideKeyboard', 
			'stopPullDownRefresh', 
        ]
        //wx api Promise化
        allMethod.map(item => {
            this[item] = function(){
                if(item.indexOf(syncMethods) > -1 || /^on\w+/.test(item) || /\w+Sync$/.test(item)){
                    return wx[item](...Array.from(arguments))
                }
                return self.__getPromise(es6.Promise, self.__getResolver(self.__defaultRequest, [item, ...Array.from(arguments)], self))
            }
        })
    }

    __getPromise(Promise, resolver){
        if(Promise) return new Promise(resolver)
        throw new Error('Promise Library does not exsit.')
    }

    __getResolver(method, args, context){
        return function(resolve, reject){
            method.apply(context, args)(resolve, reject)
        }
    }

    __defaultRequest(method='', opt={}){
        return function(resolve, reject){
            opt.success = (res) => resolve(res)
            opt.fail = (err) => reject(err)
            wx[method](opt)
        }
    }
}

export default wxService